import { getCurrentTimeParam } from "./globalTimeFilter.js";
import { API_CONFIG } from "./config.js";

document.addEventListener('DOMContentLoaded', function() {
    // 获取工单状态统计容器
    const jiagezoushiElement = document.getElementById('jiagezoushi');
    if (!jiagezoushiElement) return;

    // 创建新的工单状态统计结构 - 根据API数据调整状态项
    jiagezoushiElement.innerHTML = `
        <div class="workorder-stats-container">
            <div class="status-grid">
                <div class="status-item newly-created">
                    <div class="status-icon"></div>
                    <div class="status-name">刚创建</div>
                    <div class="status-count">0</div>
                </div>
                
                <div class="status-item completed">
                    <div class="status-icon"></div>
                    <div class="status-name">完结</div>
                    <div class="status-count">0</div>
                </div>
                
                <div class="status-item review-rejected">
                    <div class="status-icon"></div>
                    <div class="status-name">审核不通过</div>
                    <div class="status-count">0</div>
                </div>
                
                <div class="status-item review-passed">
                    <div class="status-icon"></div>
                    <div class="status-name">审核通过</div>
                    <div class="status-count">0</div>
                </div>
                
                <div class="status-item pending-review">
                    <div class="status-icon"></div>
                    <div class="status-name">待审核</div>
                    <div class="status-count">0</div>
                </div>
                
                <div class="status-item transferred">
                    <div class="status-icon"></div>
                    <div class="status-name">转交</div>
                    <div class="status-count">0</div>
                </div>
                
                <div class="status-item returned">
                    <div class="status-icon"></div>
                    <div class="status-name">退回(作废)</div>
                    <div class="status-count">0</div>
                </div>
                
                <div class="status-item rejected">
                    <div class="status-icon"></div>
                    <div class="status-name">驳回</div>
                    <div class="status-count">0</div>
                </div>
                
                <div class="status-item other">
                    <div class="status-icon"></div>
                    <div class="status-name">其他</div>
                    <div class="status-count">0</div>
                </div>
            </div>
        </div>
    `;

    // 添加样式
    const style = document.createElement('style');
    style.innerHTML = `
        .workorder-stats-container {
            padding: 15px;
            border-radius: 8px;
            height: 100%;
            border: 1px solid rgba(36, 187, 236, 0.2);
            position: relative;
            top:100px;
        }
        
        .workorder-stats-title {
            text-align: center;
            margin-bottom: 25px;
        }
        
        .workorder-stats-title h3 {
            margin: 0;
            font-size: 1.8rem;
            font-weight: 600;
            color: #24bbec;
            position: relative;
            display: inline-block;
            padding-bottom: 8px;
        }
        
        .workorder-stats-title h3::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 3px;
            background: linear-gradient(90deg, #24bbec, transparent);
            border-radius: 3px;
        }
        
        .update-time {
            color: #a2d3e8;
            font-size: 1.2rem;
            margin-top: 8px;
        }
        
        .status-grid {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 15px;
        }
        
        .status-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            background: rgba(10, 58, 124, 0.4);
            border-radius: 8px;
            padding: 15px;
            border: 1px solid rgba(36, 187, 236, 0.15);
            transition: all 0.3s ease;
        }
        
        .status-item:hover {
            transform: translateY(-5px);
            background: rgba(10, 58, 124, 0.6);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
        }
        
        .status-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-bottom: 10px;
            position: relative;
        }
        
        /* 状态图标颜色调整 */
        .newly-created .status-icon {
            background: rgba(36, 187, 236, 0.2);
            border: 2px solid #24bbec;
        }
        
        .transferred .status-icon {
            background: rgba(100, 181, 246, 0.2);
            border: 2px solid #64b5f6;
        }
        
        .completed .status-icon {
            background: rgba(36, 211, 154, 0.2);
            border: 2px solid #24d39a;
        }
        
        .rejected .status-icon {
            background: rgba(255, 107, 107, 0.2);
            border: 2px solid #ff6b6b;
        }
        
        .returned .status-icon {
            background: rgba(244, 67, 54, 0.2);
            border: 2px solid #f44336;
        }
        
        .pending-review .status-icon {
            background: rgba(156, 39, 176, 0.2);
            border: 2px solid #9c27b0;
        }
        
        .review-passed .status-icon {
            background: rgba(76, 175, 80, 0.2);
            border: 2px solid #4caf50;
        }
        
        .review-rejected .status-icon {
            background: rgba(233, 30, 99, 0.2);
            border: 2px solid #e91e63;
        }
        
        .other .status-icon {
            background: rgba(255, 193, 7, 0.2);
            border: 2px solid #ffc107;
        }
        
        .status-name {
            font-size: 1.2rem;
            color: #e6f7ff;
            font-weight: 500;
            margin-bottom: 8px;
            text-align: center;
        }
        
        .status-count {
            font-size: 1.6rem;
            font-weight: bold;
        }
        
        /* 状态计数文本颜色 */
        .newly-created .status-count {
            color: #24bbec;
        }
        
        .transferred .status-count {
            color: #64b5f6;
        }
        
        .completed .status-count {
            color: #24d39a;
        }
        
        .rejected .status-count {
            color: #ff6b6b;
        }
        
        .returned .status-count {
            color: #f44336;
        }
        
        .pending-review .status-count {
            color: #9c27b0;
        }
        
        .review-passed .status-count {
            color: #4caf50;
        }
        
        .review-rejected .status-count {
            color: #e91e63;
        }
        
        .other .status-count {
            color: #ffc107;
        }
        
        /* 动态图标效果 */
        .status-icon::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 24px;
            height: 24px;
            background-position: center;
            background-repeat: no-repeat;
            background-size: contain;
        }
        
        /* 不同状态的图标 */
        .newly-created .status-icon::before {
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%2324bbec'%3E%3Cpath d='M19 3h-1V1h-2v2H8V1H6v2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V9h14v10zm0-12H5V5h14v2z'/%3E%3C/svg%3E");
        }
        
        .transferred .status-icon::before {
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%2364b5f6'%3E%3Cpath d='M20 6h-8l-1.41-1.41C10.21 4.21 9.7 4 9.17 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-6 10h-2v-2h2v2zm0-4h-2V9h2v3zm4 4h-2v-2h2v2zm0-4h-2V9h2v3z'/%3E%3C/svg%3E");
        }
        
        .completed .status-icon::before {
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%2324d39a'%3E%3Cpath d='M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z'/%3E%3C/svg%3E");
        }
        
        .rejected .status-icon::before {
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23ff6b6b'%3E%3Cpath d='M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z'/%3E%3C/svg%3E");
        }
        
        .returned .status-icon::before {
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23f44336'%3E%3Cpath d='M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z'/%3E%3C/svg%3E");
        }
        
        .pending-review .status-icon::before {
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%239c27b0'%3E%3Cpath d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z'/%3E%3Ccircle cx='12' cy='16.5' r='1.5'/%3E%3Cpath d='M12 7c-1.1 0-2 .9-2 2c0 .6.3 1.1.8 1.4c.5.3.7.8.6 1.3c-.1.5-.5.8-1 .8c-1.1 0-2-.9-2-2s.9-2 2-2c1.1 0 2-.9 2-2s-.9-2-2-2z'/%3E%3C/svg%3E");
        }
        
        .review-passed .status-icon::before {
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%234caf50'%3E%3Cpath d='M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z'/%3E%3C/svg%3E");
        }
        
        .review-rejected .status-icon::before {
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23e91e63'%3E%3Cpath d='M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z'/%3E%3C/svg%3E");
        }
        
        .other .status-icon::before {
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23ffc107'%3E%3Cpath d='M11 15h2v2h-2zm0-8h2v6h-2zm.99-5C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z'/%3E%3C/svg%3E");
        }
    `;
    document.head.appendChild(style);

    // 初始化数据
    initWorkOrderStatus();
});

function initWorkOrderStatus() {
    const statusId = "gfwqsddgsdhsrgsb1d1231werh5tjyt"; // 工单状态统计ID
    const items = document.querySelectorAll('.status-item');

    // 监听时间变化事件
    document.addEventListener('timePeriodChanged', function() {
        updateStats();
    });

    // 更新数据函数
    function updateStats() {
        let timeParam = getCurrentTimeParam();
        console.log("发送时间",timeParam)
        // 构建API请求参数
        const params = new URLSearchParams();
        params.append('id', statusId);
        params.append('time', timeParam);
        params.append('type', '4'); // type=4

        const url = `${API_CONFIG.BASE_URL}/api/metrics/${statusId}/single-metrics-value?${params.toString()}`;

        axios.get(url)
            .then(response => {
                console.log('工单状态API响应:', response.data);
                if (response.data && response.data.code === "00000") {
                    const apiData = response.data.data;

                    // 处理状态统计
                    const stats = processStatusData(apiData);
                    updateItems(stats);
                    updateUpdateTime();
                } else {
                    console.error('工单状态数据获取失败:', response.data.msg);
                    updateItems(getDefaultStatusStats());
                }
            })
            .catch(error => {
                console.error('工单状态数据获取失败:', error);
                updateItems(getDefaultStatusStats());
            });
    }

    // 处理API数据，映射到各个状态
    function processStatusData(apiData) {
        // 根据API返回数据定义状态映射
        const stats = {
            'newly-created': 0,     // 刚创建
            'completed': 0,         // 完结
            'review-rejected': 0,   // 审核不通过
            'review-passed': 0,     // 审核通过
            'pending-review': 0,    // 待审核
            'transferred': 0,       // 转交
            'returned': 0,          // 退回(作废)
            'rejected': 0,          // 驳回
            'other': 0              // 其他
        };

        // 遍历API数据并分配到各个状态
        apiData.forEach(item => {
            const statusName = item.status;
            const count = parseInt(item.order_status_work_order_count) || 0;

            switch(statusName) {
                case '刚创建':
                    stats['newly-created'] = count;
                    break;
                case '完结':
                    stats['completed'] = count;
                    break;
                case '审核不通过':
                    stats['review-rejected'] = count;
                    break;
                case '审核通过':
                    stats['review-passed'] = count;
                    break;
                case '待审核':
                    stats['pending-review'] = count;
                    break;
                case '转交':
                    stats['transferred'] = count;
                    break;
                case '退回（作废）':
                    stats['returned'] = count;
                    break;
                case '驳回':
                    stats['rejected'] = count;
                    break;
                case '其他':
                    stats['other'] = count;
                    break;
            }
        });

        return stats;
    }

    // 默认状态统计
    function getDefaultStatusStats() {
        return {
            'newly-created': 0,
            'completed': 0,
            'review-rejected': 0,
            'review-passed': 0,
            'pending-review': 0,
            'transferred': 0,
            'returned': 0,
            'rejected': 0,
            'other': 0
        };
    }

    // 更新显示
    function updateItems(stats) {
        items.forEach(item => {
            // 获取状态类名（如 'newly-created', 'completed'）
            const statusClass = Array.from(item.classList).find(cls =>
                [
                    'newly-created', 'completed', 'review-rejected',
                    'review-passed', 'pending-review', 'transferred',
                    'returned', 'rejected', 'other'
                ].includes(cls)
            );

            if (!statusClass) return;

            const countElement = item.querySelector('.status-count');
            const targetValue = stats[statusClass];

            if (typeof targetValue === 'number') {
                animateCount(countElement, targetValue);
            }
        });
    }

    // 更新更新时间
    function updateUpdateTime() {
        const now = new Date();
        const hours = now.getHours().toString().padStart(2, '0');
        const minutes = now.getMinutes().toString().padStart(2, '0');
        const seconds = now.getSeconds().toString().padStart(2, '0');

        const updateTimeElement = document.getElementById('workorder-update-time');
        if (updateTimeElement) {
            updateTimeElement.textContent = `更新时间: ${hours}:${minutes}:${seconds}`;
        }
    }

    // 初始调用
    updateStats();

    // 每8秒更新一次数据
    setInterval(updateStats, 80000000);
}

// 数字动画效果
function animateCount(element, target) {
    const duration = 1000;
    const start = parseInt(element.textContent.replace(/,/g, '')) || 0;
    const diff = target - start;
    const startTime = performance.now();

    function updateCount(timestamp) {
        const runtime = timestamp - startTime;
        const progress = Math.min(runtime / duration, 1);

        const currentValue = Math.floor(start + diff * progress);
        element.textContent = currentValue.toLocaleString();

        if (runtime < duration) {
            requestAnimationFrame(updateCount);
        } else {
            element.textContent = target.toLocaleString();
        }
    }

    requestAnimationFrame(updateCount);
}
